package org.leiyang.service.impls;

import org.leiyang.common.dtos.TestRequestVO;
import org.leiyang.service.combine.CombineService1;
import org.leiyang.service.feign.RemoteService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@Service
public class CombineService1Impl implements CombineService1 {
    private static final Logger log = LoggerFactory.getLogger(CombineService1Impl.class);
    private final RemoteService remoteService;

    public CombineService1Impl(RemoteService remoteService) {
        this.remoteService = remoteService;
    }


    @Override
    public Flux<String> combineA(TestRequestVO testRequestVO) {
        Flux<String> rInvoke2 = remoteService.listNames(testRequestVO);
        Mono<String> rInvoke1 = remoteService.syncShowOneInfo(testRequestVO.getRegisterName());
//        String invoke3 = remoteService.showOneInfo("example");
        Mono<String> rInvoke3 = testUsingWhen();


        //并行
        return Flux.zip(rInvoke1, rInvoke2, rInvoke3).map(s -> {
            String t1 = s.getT1();
            String t2 = s.getT2();
            String t3 = s.getT3();
            return String.format("invoke1:%s, invoke2: %s, invoke3: %s", t1, t2, t3);
        });
    }

    @Override
    public Flux<String> combineB(TestRequestVO testRequestVO) {
        Flux<String> rInvoke2 = remoteService.listNames(testRequestVO);
        Mono<String> rInvoke1 = remoteService.syncShowOneInfo(testRequestVO.getRegisterName());
        //串行
        return rInvoke2.flatMap(p -> {
            return rInvoke1.map(s -> {
                return p.concat(":").concat(s);
            });
        });
    }

    private Mono<String> testUsingWhen() {
        return Mono.usingWhen(Mono.fromSupplier(this::getContentInfo), this::concateStr, this::doClose);
    }

    private Mono<Void> doClose(String empty){
//        return Mono.defer(Mono::empty);
        return Mono.empty();
    }

    private String getContentInfo() {
        return "student";
    }

    private Mono<String> concateStr(String content){
        return Mono.just("prefix: ".concat(content));
    }
}
